var canvas;
var context;
var h;
var w;
var girlPic=new Image();
var starImage=new Image();
var num=60;
var stars=[];
var lastTime;
var deltaTime;//与上一帧刷新的时间间隔
function init(){
  canvas=document.getElementById("canvas");
  context=canvas.getContext('2d');
  w=canvas.width;
  h=canvas.height;
  starImage.src="images/star.png";
  girlPic.src="images/girl.jpg";
  for(var i=0;i<num;i++){
  	var obj=new starObj();
  	stars.push(obj);
  	stars[i].init();
  }
  lastTime=Date.now();
  setInterval(function(){
  	time();
  	 drawBackground();
  	 drawGirl();
  	 drawStars();
  },40);
}
document.body.onload=init;

function time(){
	var now=Date.now();
    deltaTime=now-lastTime;
    lastTime=now;
}
function drawGirl(){
    context.drawImage(girlPic,100,150,600,300);
}

function drawBackground(){
   context.fillStyle="#ccc"
   context.fillRect(0,0,w,h);
   context.fill();
}

//随机生成星星
var starObj=function(){
	this.x;
	this.y;
	this.picNo;
	this.timer;
}

starObj.prototype.init=function(){
	this.x=Math.random()*600+100;
	this.y=Math.random()*300+150;
	this.picNo=Math.floor(Math.random()*7);
	this.timer=0;
}
starObj.prototype.update=function(){
	this.timer+=deltaTime;
	if(this.timer>50){
		this.picNo+=1;
		this.picNo%=7;
		this.timer=0;
	}
}
starObj.prototype.draw=function(){
	context.drawImage(starImage,this.picNo*7,0,7,7,this.x,this.y,7,7);
}

function drawStars(){
	for(var i=0;i<num;i++){
		stars[i].update();
		stars[i].draw();
	}
}